<template>
  <div class="app-container">
    <el-row>
      
      <el-col
        :span="24"
        :xs="24"
      >
        <div class="topBox">
          <div class="selectUserData">
            <el-form
              :model="queryParams"
              ref="queryRef"
              :inline="true"
              v-show="showSearch"
              label-width="68px"
            >
              <div style="display: flex;justify-content: space-between;">
                <div>
                  <el-form-item
                    label="班级"
                    prop="userName"
                  >
                    <el-select
                      v-model="queryParams.deptId"
                      placeholder="请选择班级"
                      style="width: 256px"
                      @change="handleQuery"
                    >
                      <el-option
                        v-for="item in departmentsList"
                        :key="item.deptId"
                        :label="item.deptName"
                        :value="item.deptId"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="角色"
                    prop="roleName"
                  >

                    <el-select
                      v-model="queryParams.roleId"
                      placeholder="请选择角色"
                      style="width: 256px"
                      @change="handleQuery"
                    >
                      <el-option
                        v-for="item in rolesList"
                        :key="item.roleId"
                        :label="item.roleName"
                        :value="item.roleId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    label="姓名"
                    prop="status"
                  >

                    <el-select
                      v-model="queryParams.nickName"
                      placeholder="请选择姓名"
                      style="width: 256px"
                      @change="handleQuery"
                    >
                      <el-option
                        v-for="item in nickNameList"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>

                  <el-form-item>
                    <img
                      src="@/assets/images/reset.png"
                      style="cursor: pointer; width: 24px; height: 24px;"
                      @click="resetData"
                    >
                    <span
                      style="color: #363636; font-size: 14px;cursor: pointer;margin-left: 8px;"
                      @click="resetData"
                    >重置数据</span>
                  </el-form-item>
                </div>
                <div>
                  <el-form-item>
                    <el-button
                      plain
                      style="width: 80px;height: 40px;border: 1px solid #5974FF;color:#5974FF;font-size: 16px;"
                      :disabled="selectionUserData.length == 0"
                      @click="exportUserData"
                    >
                      <span>导出</span>
                    </el-button>
                  </el-form-item>
                </div>
              </div>

            </el-form>
          </div>

          <div class="userData">
            <el-row
              :gutter="10"
              class="mb8"
              style="display: flex; justify-content: space-between;align-items: center;"
            >
              <el-col :span="
          1.5">
                <el-button
                  plain
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['system:user:remove']"
                  style="width: 112px;height: 40px;border: 1px solid #5974FF;font-size: 16px;color: #5974FF;"
                >批量删除</el-button>
              </el-col>
              <div>
                <el-col :span="1.5">
                  <el-dropdown @command="handleAdd1">
                    <el-button
                      type="primary"
                      plain
                      v-hasPermi="['system:user:add']"
                      style="width: 144px;height: 40px;background: #5974FF;font-size: 16px;color: #FFFFFF;border-radius: 6px;"
                    >
                      <el-icon style="margin-right: 11px;">
                        <Plus />
                      </el-icon>
                      <span>新建账号</span>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu style="width: 144px;">
                        <el-dropdown-item command="add">新建账号</el-dropdown-item>

                        <el-dropdown-item
                          command="batchAdd"
                          style="width: 144px;"
                        >
                          <el-upload
                            ref="upload"
                            action=""
                            :auto-upload="false"
                            :show-file-list="false"
                            accept=".xlsx, .xls"
                            :on-change="handleFileChange"
                          ></el-upload>
                          批量新建
                        </el-dropdown-item>

                      </el-dropdown-menu>

                    </template>
                  </el-dropdown>
                </el-col>
              </div>
              
            </el-row>
            <el-table
              v-loading="loading"
              :data="userList"
              @selection-change="handleSelectionChange"
              style="margin-top: 24px;"
            >
              <el-table-column
                type="selection"
                width="50"
                align="center"
              />
              <el-table-column
                label="编号"
                width="50"
                align="center"
              >
                <template #default="scope">
                  <!-- 生成不重复的序号 -->
                  {{ (queryParams.pageNum - 1)* queryParams.pageSize + scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                label="姓名"
                align="center"
                key="nickName"
                prop="nickName"
                v-if="columns[1].visible"
                :show-overflow-tooltip="true"
              />

              <el-table-column
                label="角色"
                align="center"
                key="roleName"
                prop="roles"
              >
                <template #default="scope">
                  <span
                    v-for="(item, index) in scope.row.roles"
                    :key="index"
                  >
                    <span>{{ item.roleName }}</span>
                    <span v-if="index !== scope.row.roles.length - 1"> / </span>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                label="账号"
                align="center"
                key="userName"
                prop="userName"
                :show-overflow-tooltip="true"
                v-if="columns[2].visible"
              />
              <el-table-column
                label="班级"
                align="center"
                key="deptName"
                prop="dept.deptName"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
              <el-table-column
                label="创建时间"
                align="center"
                sortable
                prop="createTime"
                v-if="columns[6].visible"
                width="260"
              >
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              
              <el-table-column
                label="密码"
                align="center"
              >
                <template #default="scope">
                  <el-tooltip
                    content="重置密码"
                    placement="top"
                    v-if="scope.row.userId !== 1"
                  >
                    <el-button
                      link
                      type="primary"
                      text
                      @click="handleResetPwd(scope.row)"
                      v-hasPermi="['system:user:resetPwd']"
                    >
                      <span style="font-size: 14px;color: #5974FF;">重置密码</span>
                    </el-button>
                  </el-tooltip>
                </template>
              </el-table-column>
              

              <el-table-column
                label="操作"
                align="center"
                width="150"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-tooltip
                    content="修改"
                    placement="top"
                    v-if="scope.row.userId !== 1"
                  >
                    <el-button
                      link
                      type="primary"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['system:user:edit']"
                    >
                      <el-icon style="color: #5974FF;font-size: 16px;">
                        <EditPen />
                      </el-icon>
                      <span style="color: #363636;font-size: 12px;">编辑</span>
                    </el-button>
                  </el-tooltip>
                  <el-tooltip
                    content="删除"
                    placement="top"
                    v-if="scope.row.userId !== 1"
                  >
                    <el-button
                      link
                      type="primary"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['system:user:remove']"
                    >
                      <el-icon style="color: #f99d38;font-size: 16px;">
                        <Delete />
                      </el-icon>
                      <span style="color: #363636;font-size: 12px;">
                        删除
                      </span>
                    </el-button>
                  </el-tooltip>
                  =
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      align-center
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="80px"
        style="display: flex;flex-direction: column;align-items: center;"
      >
        <el-row>
         =
          <el-col>
            <el-form-item
              label="姓名"
              prop="nickName"
            >
              <el-input
                style="height: 36px;width: 340px;"
                v-model="form.nickName"
                placeholder="请输入用户名称"
                maxlength="30"
              />
            </el-form-item>

          </el-col>
        </el-row>

        <el-row>

          <el-col>
            <el-form-item
              width="320"
              label="账号"
              prop="userName"
            >
              <el-input
                style="height: 36px;width: 340px;"
                v-model="form.userName"
                placeholder="请输入账号"
                maxlength="30"
              />
            </el-form-item>

          </el-col>
        </el-row>

        <el-form-item
          label="班级"
          prop="deptId"
        >
         
          <el-select
            v-model="form.deptId"
            placeholder="请选择班级"
            style="width: 340px;height: 36px;"
          >
            <el-option
              v-for="item in departmentsList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="角色"
          prop="roleIds"
        >

          <el-select
            v-model="form.roleIds"
            placeholder="请选择角色"
            style="width: 340px;height: 36px;"
          >

            <el-option
              :value="1"
              label="超级管理员"
            >超级管理员</el-option>
            <el-option
              :value="2"
              label="普通角色"
            >普通角色</el-option>
          </el-select>
        </el-form-item>

       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            plain
            @click="cancel"
            class="cancelBtn"
          >取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm"
            class="saveBtn"
          ><span style="color: #FFFFFF;font-size: 16px;">
              保 存
            </span></el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size:12px;vertical-align: baseline;"
              @click="importTemplate"
            >下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            @click="submitFileForm"
          >确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <BatchAddDialog
      ref="batchAddDialogRef"
      @download="importTemplate"
      @batchUpload="handleFileChange"
    ></BatchAddDialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import { changeUserStatus, listUser, resetUserPwd, delUser, getUser, updateUser, addUser, deptTreeSelect, roleList, departmentList, getNickName } from "@/api/system/user";
import { get } from '@vueuse/core';

// 引入批量新建提示弹窗
import BatchAddDialog from './batchAddDialog.vue';

import { exportExcel, importExcel } from "@/utils/peak-tools.js";
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict("sys_normal_disable", "sys_user_sex");

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptName = ref("");
const deptOptions = ref(undefined);
const initPassword = ref(undefined);
const postOptions = ref([]);
const roleOptions = ref([]);
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});
// 列显隐信息
const columns = ref([
  { key: 0, label: `用户编号`, visible: true },
  { key: 1, label: `用户名称`, visible: true },
  { key: 2, label: `用户昵称`, visible: true },
  { key: 3, label: `部门`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `状态`, visible: true },
  { key: 6, label: `创建时间`, visible: true }
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: undefined,
    phonenumber: undefined,
    status: undefined,
    deptId: undefined,
    roleId: undefined,
    deptId: undefined,
  },
  rules: {
    nickName: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "用户名称长度必须介于 2 和 20 之间", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value.trim() === '') {
            callback(new Error('请输入非空值且不能包含空格'));
          } else if (/\s/.test(value)) {
            // 使用正则表达式检查是否有空格  
            callback(new Error('输入不能包含空格'));
          } else {
            callback();
          }
        }, trigger: "blur"
      }
    ],
    userName: [{ required: true, message: "用户账号不能为空", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value && /[\u4e00-\u9fa5]/.test(value)) {
          callback(new Error('用户账号不能包含中文'));
        } else {
          callback();
        }
      }, trigger: "blur"
    },
    {
      validator: (rule, value, callback) => {
        if (value.trim() === '') {
          callback(new Error('请输入非空值且不能包含空格'));
        } else if (/\s/.test(value)) {
          // 使用正则表达式检查是否有空格  
          callback(new Error('输入不能包含空格'));
        } else {
          callback();
        }
      }, trigger: "blur"
    }
    ],
    deptId: [{ required: true, message: "班级不能为空", trigger: "blur" },],
    roleIds: [{ required: true, message: "角色不能为空", trigger: "blur" },]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/** 查询部门下拉树结构 */
function getDeptTree () {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
const userSelect = ref([])
/** 查询用户列表 */
function getList () {
  loading.value = true;
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    loading.value = false;
    userList.value = res.rows;
    total.value = res.total;
  });

  userList.value.forEach(item => {
    userSelect.value.push(item.nickName)
  })


};
/** 节点单击事件 */
function handleNodeClick (data) {
  queryParams.value.deptId = data.id;
  handleQuery();
};
/** 搜索按钮操作 */
function handleQuery () {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
function resetQuery () {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
};
/** 删除按钮操作 */
function handleDelete (row) {
  const userIds = row.userId || ids.value;
  // proxy.$modal.confirm('是否确认删除？', {
  //   confirmButtonClass: 'cinformBtn',
  //   cancelButtonClass: 'cancelBtn'
  // }).then(function () {
  //   return delUser(userIds);
  // }).then(() => {
  //   getList();
  //   proxy.$modal.msgSuccess("删除成功");
  // }).catch(() => { });
  ElMessageBox.confirm('是否确认删除', '系统提示', {
    type: 'warning',
    confirmButtonClass: 'confirmDeleteBtn',
    cancelButtonClass: 'cancelDeleteBtn'
  }).then(function () {
    return delUser(userIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { })
};
/** 导出按钮操作 */
function handleExport () {
  proxy.download("system/user/export", {
    ...queryParams.value,
  }, `user_${new Date().getTime()}.xlsx`);
};
/** 用户状态修改  */
function handleStatusChange (row) {
  let text = row.status === "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗?').then(function () {
    return changeUserStatus(row.userId, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0";
  });
};
/** 更多操作 */
function handleCommand (command, row) {
  switch (command) {
    case "handleResetPwd":
      handleResetPwd(row);
      break;
    case "handleAuthRole":
      handleAuthRole(row);
      break;
    default:
      break;
  }
};
/** 跳转角色分配 */
function handleAuthRole (row) {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
};
/** 重置密码按钮操作 */
function handleResetPwd (row) {
  proxy.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return "不能包含非法字符：< > \" ' \\\ |"
      }
    },
  }).then(({ value }) => {
    resetUserPwd(row.userId, value).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value);
    });
  }).catch(() => { });
};
const selectionUserData = ref([])
/** 选择条数  */
function handleSelectionChange (selection) {
  selectionUserData.value = selection
  ids.value = selection.map(item => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 导入按钮操作 */
function handleImport () {
  upload.title = "用户导入";
  upload.open = true;
};
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};
/** 提交上传文件 */
function submitFileForm () {
  proxy.$refs["uploadRef"].submit();
};
/** 重置操作表单 */
function reset () {
  form.value = {
    userId: undefined,
    deptId: undefined,
    userName: undefined,
    nickName: undefined,
    password: undefined,
    phonenumber: undefined,
    email: undefined,
    sex: undefined,
    status: "0",
    remark: undefined,
    postIds: [],
    roleIds: []
  };
  proxy.resetForm("userRef");
};
/** 取消按钮 */
function cancel () {
  open.value = false;
  reset();
};
/** 新增按钮操作 */
function handleAdd () {
  reset();
  getUser().then(response => {
    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    open.value = true;
    title.value = "新增用户";
    form.value.password = initPassword.value;
  });
};
/** 修改按钮操作 */
function handleUpdate (row) {

  reset();
  const userId = row.userId || ids.value;
  getUser(userId).then(response => {
    console.log(response)


    postOptions.value = response.posts;
    roleOptions.value = response.roles;
    form.value = response.data;
    form.value.postIds = response.postIds;
    form.value.roleIds = response.roleIds[0];
    open.value = true;
    title.value = "修改用户";
    form.password = "";
    console.log(response.roleIds[0])
    console.log(form.value)
  });
};
/** 提交按钮 */
function submitForm () {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.userId != undefined) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser([{ ...form.value }]).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

// 查询
function selectUser () {
  getList()
}

const rolesList = ref([])
async function getRoleList () {
  const res = await roleList({ pageNum: 100, pageSize: 100 })
  rolesList.value = res.rows
}

function clearData () {
  queryParams.value.roleId = null
  getList()
}

function clearData2 () {
  queryParams.value.deptId = null
  getList()
}

// 获取部门列表
const departmentsList = ref([])
async function getDepartmentList () {
  const res = await departmentList()
  departmentsList.value = res.data
}
getDepartmentList()


// 点击重置数据
function resetData () {
  queryParams.value.nickName = null
  queryParams.value.deptId = null
  queryParams.value.roleId = null
  getList()
}


// 重写下载模板操作
async function importTemplate () {
  const res = await exportExcel(
    "账号管理导入模板.xlsx",
    {
      姓名: "nickName",
      角色: "roleName",
      账号: "userName",
      班级: "deptName",
    },
    [
      {
        nickName: "张三",
        roleName: "普通角色或超级管理员",
        userName: "admin111",
        deptName: "测试部门",
      }
    ],
    (sheet) => {
      let columnWidth = [16, 10, 10, 32, 16, 10, 30, 30, 30, 10];
      sheet["!cols"] = columnWidth.map((width) => ({
        width,
      }));
      return sheet;
    }
  )
}

getRoleList()

getDeptTree();
getList();


// 重写导出数据
async function exportUserData () {
  let list = JSON.parse(JSON.stringify(selectionUserData.value))
  list.map(item => {
    item.roleName = item.roles.map(item => {
      return item.roleName
    })
  })
  list.map(item => {
    return item.roleName = item.roleName.join("/")
  })
  list.map(item => {
    item.deptName = item.dept.deptName
  })


  let tableTemplateHead = {
    姓名: "nickName",
    角色: "roleName",
    账号: "userName",
    班级: "deptName",
  }
  const res = await exportExcel("客户信息.xlsx", tableTemplateHead, list, (sheet) => {
    let columnWidth = [14, 16, 25, 10, 14, 30, 30, 30, 10];
    sheet["!cols"] = columnWidth.map((wch) => ({
      wch,
    }));
    return sheet;
  })


}

const batchAddDialogRef = ref(null)

function handleAdd1 (command) {
  if (command === "add") {
    handleAdd()
  } else if (command = "batchAdd") {
    batchAddDialogRef.value.dialogVisible = true
  }
}

const uploadFile = ref(null)
function containsChinese (str) {
  return /[\u4e00-\u9fa5]/.test(str)
}

function isHaveChinese (data) {
  return data.some((item) => containsChinese(item.userName));
}

// 上传文件的方法
async function handleFileChange (file) {
  uploadFile.value = file
  let tableTemplateHead = {
    姓名: "nickName",
    角色: "roleName",
    账号: "userName",
    班级: "deptName",
  }
  try {
    const res = await importExcel(file.raw, tableTemplateHead);
    let uploadAccountData = {}
    if (Array.isArray(res.data) && !isHaveChinese(res.data)) {
      console.log(res)
      let deptMap = new Map()
      departmentsList.value.forEach(item => {
        deptMap.set(item.deptName, item.deptId)
      })
      uploadAccountData = res.data.map(item => {
        let roleIds = null
        if (item.roleName === '超级管理员') {
          roleIds = 1
        } else if (item.roleName === '普通角色') {
          roleIds = 2
        } else {
        }
        let deptId = deptMap.get(item.deptName)
        return {
          ...item,
          roleIds,
          deptId
        }
      })
      console.log(uploadAccountData)
      for (let i = 0; i < res.data.length; i++) {
        if (!res.data[i].hasOwnProperty('nickName')) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据姓名不能为空`
          })
        } else if (String(res.data[i].nickName).length < 2) {
          return ElMessage({
            type: 'error',
            message: `第${i + 1}个数据姓名长度不能小于2`
          })
        } else if (String(res.data[i].nickName).length > 30) {
          return ElMessage({
            type: 'error',
            message: `第${i + 1}个数据姓名长度不能大于30`
          })
        }
        else if (!res.data[i].hasOwnProperty('roleName')) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据角色不能为空`
          })
        } else if (!(res.data[i].roleName == "超级管理员" || res.data[i].roleName == "普通角色")) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据角色名称填写有误，应填写超级管理员或普通角色请检查`
          })
        } else if (!res.data[i].hasOwnProperty('userName')) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据账号不能为空`
          })
        } else if (String(res.data[i].userName).length > 20) {
          return ElMessage({
            type: 'error',
            message: `第${i + 1}个数据账号长度不能大于20`
          })
        } else if (!res.data[i].hasOwnProperty('deptName')) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据班级不能为空`
          })
        } else if (!String(res.data[i].deptName).includes('部门') || String(res.data[i].deptName).length < 4) {
          return ElMessage({
            type: "error",
            message: `第${i + 1}个数据班级信息填写错误`
          })
        }
      }
      for (let i = 0; i < res.data.length; i++) {
        let deptName = res.data[i].deptName
        if (deptMap.has(deptName)) {
          res.data[i].deptId = deptMap.get(deptName)
        } else {
          return ElMessage({
            type: 'error',
            message: '您传入的班级名称有误，请检查'
          })
        }
      }


    } else if (Array.isArray(res.data) && isHaveChinese(res.data)) {
      return ElMessage({
        type: 'error',
        message: '批量上传的文件中，账号信息不允许包含中文，请检查'
      })
    } else if (typeof res === 'object' && res !== null) {
      console.log(456)
      uploadFile.value = null
      proxy.$modal.msgError(res.msg);
    }


    await addUser(uploadAccountData)
    uploadFile.value = null
    getList()
    proxy.$modal.msgSuccess("批量导入成功");

  } catch (error) {
    console.log(error)
  }
}

const nickNameList = ref(null)

// 获取姓名列表
async function getNickNameList () {
  const res = await getNickName()
  nickNameList.value = res.data
}
getNickNameList()
</script>

<style scoped lang="scss">
::v-deep(.pagination-container) {
  height: 50px;
}

.app-container {
  padding: 32px 32px 0 32px;
}

.topBox {
  min-height: 936px;
  background: #ffffff;
  border-radius: 10px 10px 10px 10px;

  .userData {
    padding: 24px 24px 0 32px;
  }
}

.selectUserData {
  border-bottom: 1px solid #d4d4d4;
  padding-top: 24px;
  padding-bottom: 10px;
}

::v-deep(.el-table__header) {
  height: 56px;
}

::v-deep(.el-table__row) {
  height: 56px;
}

.saveBtn {
  width: 108px;
  height: 40px;
  border: 1px solid #5974ff;
  background: #5974ff;
  border-radius: 6px 6px 6px 6px;
}

.cancelBtn {
  width: 108px;
  height: 40px;
  border: 1px solid #5974ff;
  border-radius: 6px 6px 6px 6px;
  color: #5974ff;
}
// 模态框居中显示
::v-deep(.el-dialog:not(.is-fullscreen)) {
  margin: auto !important;
}

::v-deep(.confirmBtn) {
  width: 108px;
  height: 40px !important;
  border: 1px solid #5974ff !important;
  border-radius: 6px 6px 6px 6px;
  color: #5974ff;
}
</style>
